<template>
  <div class="main" style="height: 100%">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <div>
        <el-select
          size="small"
          v-model="params.area"
          filterable
          placeholder="请选择省份"
          clearable
        >
          <el-option
            v-for="item in provinceOptions"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="params.userName"
          placeholder="请输入创建人"
          size="small"
          style="width: 250px; margin-left: 15px"
        ></el-input>
        <el-select
          style="margin-left: 15px"
          size="small"
          v-model="params.status"
          filterable
          placeholder="请选择审核状态"
          clearable
        >
          <el-option label="未审核" value="0"> </el-option>
          <el-option label="已审核" value="2"> </el-option>
          <el-option label="已驳回" value="1"> </el-option>
        </el-select>
        <el-select
          style="margin: 0 20px"
          size="small"
          v-model="params.type"
          filterable
          placeholder="请选择费用类型"
          clearable
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button size="small" type="primary" @click="searchList"
          >查询</el-button
        >
      </div>
      <div>
        <el-button size="small" type="primary" @click="_downLoad2"
          >导出</el-button
        >
        <el-button
          size="small"
          v-if="authority.includes(1021)"
          type="primary"
          @click="addRecord"
          >新增记录</el-button
        >
      </div>
    </div>
    <div style="margin-top: 20px; height: calc(100% - 120px); overflow: scroll">
      <el-table
        :data="dataList"
        border
        show-summary
        style="overflow: auto"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
        :cellStyle="{
          textAlign: 'center',
          fontSize: '12px',
        }"
      >
        <el-table-column prop="id" label="id" width="100px"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间"></el-table-column>
        <el-table-column prop="userName" label="创建人"></el-table-column>
        <el-table-column prop="areaName" label="仓库"></el-table-column>
        <el-table-column label="类型">
          <template slot-scope="scope">
            <div v-if="scope.row.status === 0" style="color: #f56c6c">
              {{ scope.row.type }}
            </div>
            <div v-else>
              {{ scope.row.type }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="承担主体">
          <template slot-scope="scope">
            <span v-if="scope.row.optioner == 7">其他</span>
            <span v-if="scope.row.optioner == 1"
              >破损（运损、打包不牢实 ： 仓库责任）</span
            >
            <span v-if="scope.row.optioner == 2"
              >工厂质量问题(2024.12.06之前判责规则暂停用)</span
            >
            <span v-if="scope.row.optioner == 3"
              >少发、漏发、错发（仓库责任）</span
            >
            <span v-if="scope.row.optioner == 4">安装细节问题（安装）</span>
            <span v-if="scope.row.optioner == 5"
              >店铺尺寸问题(装修、设计图纸不符)</span
            >
            <span v-if="scope.row.optioner == 6"
              >安装好后人为损坏（加盟商，店员）</span
            >
            <span v-if="scope.row.optioner == 8">缺货</span>
            <span v-if="scope.row.optioner == 9">装修尺寸问题：装修方责任</span>
            <span v-if="scope.row.optioner == 10"
              >设计图纸问题：品牌方责任</span
            >
            <span v-if="scope.row.optioner == 11">业务对接问题</span>
            <span v-if="scope.row.optioner == 12">CAD问题</span>
            <span v-if="scope.row.optioner == 13">系统问题</span>
            <span v-if="scope.row.optioner == 14">多发（仓库责任）</span>
            <span v-if="scope.row.optioner == 15"
              >破损、变形（工厂质量问题：使用时出现问题、保修期内）</span
            >
            <span v-if="scope.row.optioner == 16">店铺丢失</span>
            <span v-if="scope.row.optioner == 17">人为破坏</span>
            <span v-if="scope.row.optioner == 18"
              >工厂质量问题（工厂到货未检查到位： 仓库责任 ）</span
            >
            <span v-if="scope.row.optioner == 19"
              >工厂质量问题（工厂质量：焊接不牢固、制作尺寸错误、混焊等）</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="amount" label="金额"></el-table-column>
        <el-table-column label="凭证">
          <template slot-scope="scope">
            <div v-if="scope.row.imgs">
              <el-image
                v-for="(v, i) in scope.row.preImg"
                :key="i"
                style="width: 50px; height: 50px"
                ref="preview"
                :src="host + v"
                :preview-src-list="scope.row.preImg.map((img) => host + img)"
              >
              </el-image>
            </div>
            <!-- <el-image v-if='props.row.imgs':src="'https://'+ props.row.imgs" style="width:50px;height:50px;"></el-image> -->
            <el-tag v-else>暂无凭证</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="财务打款">
          <template slot-scope="scope">
            <div v-if="scope.row.paymentImg">
              <el-image
                v-for="(v, i) in [scope.row.paymentImg]"
                :key="i"
                style="width: 50px; height: 50px"
                ref="preview"
                :src="host + v"
                :preview-src-list="[host + v]"
              >
              </el-image>
            </div>
            <!-- <el-image v-if='props.row.imgs':src="'https://'+ props.row.imgs" style="width:50px;height:50px;"></el-image> -->
            <el-tag v-if="!scope.row.paymentImg && scope.row.status == 0"
              >未打款</el-tag
            >
            <el-tag
              v-if="scope.row.status == '1'"
              style="color: #fff; background-color: #f9a7a7"
              >已驳回</el-tag
            >
            <span style="display: block" v-if="scope.row.status == '1'">{{
              '驳回理由：' + (scope.row.reason || '无')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-popover
              placement="right"
              :title="`确定删除id为{` + scope.row.id + `}的数据？`"
              width="400"
              trigger="click"
            >
              <el-button
                type="danger"
                size="small"
                style="float: right; margin-top: 10px"
                @click="deleteList(scope.row)"
                >确认删除
              </el-button>
              <el-link
                type="danger"
                slot="reference"
                size="small"
                v-if="scope.row.status === 1"
                >删除
              </el-link>
            </el-popover>
            <el-link
              style="color: #66b1ff; margin-left: 15px"
              @click="approval(scope.row)"
              v-if="scope.row.status == '0'"
              >审批
            </el-link>
            <el-link
              style="color: #f5b330; margin-left: 15px"
              v-if="[1].includes(scope.row.status)"
              @click="_edit(scope.row)"
            >
              编辑
            </el-link>
            <el-link
              style="color: rebeccapurple; margin-left: 15px"
              v-if="[2, 1].includes(scope.row.status)"
              @click="review(scope.row, 0)"
              ><i class="el-icon-refresh-left" style="color: rebeccapurple"></i>
              撤回
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="padding-top: 20px">
      <el-pagination
        style="border-top: 1px solid #eee; padding-top: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNumber"
        :page-sizes="[5, 10, 20, 30, 50]"
        :page-size="20"
        layout="total, sizes, prev, pager, next, jumper"
        align="right"
        :total="totalCount"
      >
      </el-pagination>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="新增仓库台帐记录"
      :visible.sync="ledgerStatus"
      width="45%"
      @closed="loading = false"
    >
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <el-select
          v-model="createForm.provinceId"
          style="width: 45%"
          filterable
          placeholder="请选择省份"
        >
          <el-option
            v-for="item in provinceOptions"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          >
          </el-option>
        </el-select>
        <el-select
          style="width: 45%"
          v-model="createForm.typeId"
          filterable
          placeholder="请选择费用类型"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div
        style="
          margin: 20px 0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <el-input-number
          style="width: 45%"
          v-model="createForm.price"
        ></el-input-number>
        <el-input
          style="width: 45%"
          type="text"
          v-model="createForm.remark"
          placeholder="请输入备注"
        ></el-input>
      </div>
      <div
        style="
          margin: 20px 0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <el-select
          clearable
          v-model="createForm.optioner"
          placeholder="请选择承担主体"
          filterable
          style="width: 45%"
        >
          <el-option
            v-for="item in SaleTypeData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div style="width: 45%">
        <div style="width: 80px; text-align: center; margin-top: 30px">
          报销凭证：
        </div>
        <div class="div">
          <!--            <div>-->
          <!--              <upload title="" @imgUrl="getImageUrl" :clearImgUrl='afterVoucherClearImgUrl'-->
          <!--                      uploadType="drag" :multilineStatus="true" />-->
          <!--            </div>-->

          <span style="color: gray; font-size: 12px"
            >(粘贴复制即可上传图片)</span
          >
          <div
            class="div"
            style="
              display: flex;
              align-items: center;
              width: 500px;
              flex-wrap: wrap;
            "
          >
            <div v-for="(v, i) in preSalesImg" style="display: flex">
              <el-image
                :key="i"
                style="width: 50px; height: 50px"
                ref="preview"
                :src="host + v"
                :preview-src-list="preSalesImg.map((img) => host + img)"
              >
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
          <!--            <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span>-->
          <!--            <el-image v-for='(v, i) in preSalesImg' :key="i" style="width: 50px; height: 50px"-->
          <!--                      ref="preview" :src="host+v" :preview-src-list="preSalesImgList">-->
          <!--            </el-image>-->
        </div>

        <!--                <upload uploadType="drag" @imgUrl="getUrl" title="费用凭证"></upload>-->
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="ledgerStatus = false">取 消</el-button>
        <el-button type="primary" @click="submitCreateForm" :loading="loading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="adiutDialog"
      width="30%"
      title="财务审批"
      center
    >
      <span>付款凭证（通过填）：复制粘贴即可上传图片</span>
      <div style="display: flex; width: 500px; flex-wrap: wrap; height: 100px">
        <div v-for="(v, i) in preSalesImg" style="display: flex">
          <el-image
            :key="i"
            style="width: 50px; height: 50px"
            ref="preview"
            :src="host + v"
            :preview-src-list="[host + v]"
          >
          </el-image>
          <div @click="deletePic(i)">
            <el-icon name="delete"></el-icon>
          </div>
        </div>
      </div>
      <span>驳回理由：（驳回填）</span>
      <el-input v-model="reason" type="textarea"></el-input>
      <span slot="footer">
        <el-button
          style="background-color: #dd6161; color: #ffffff"
          @click="review('', 1)"
          >驳 回</el-button
        >
        <el-button
          style="background-color: #66b1ff; color: #ffffff"
          @click="review('', 2)"
          >通 过</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ExcelJS from 'exceljs'
import upload from '@/RayComponents/upload.vue'
import axios from 'axios'
import quinn from '../../../utils/quinn'
import store from '../../../store'

export default {
  name: 'AreaLedger',
  components: {
    upload,
  },
  data() {
    return {
      loading: false,
      apiName: 'newAreaLedgerList',
      totalCount: 0,
      previewImg: [],
      host: this.$imgHost,
      preSalesImg: [],
      preSalesImgList: [],
      params: {
        pageNumber: 1,
        pageSize: 20,
        type: '',
        area: '',
        status: '',
      },
      ledgerStatus: false,
      adiutDialog: false,
      typeId: '',
      reason: '',
      typeOptions: [],
      provinceId: '',
      SaleTypeData: '',
      createForm: {
        typeId: '',
        provinceId: '',
        price: '',
        remark: '',
        optioner: '',
      },
      provinceOptions: [],
      dataList: [],
      authority: [],
    }
  },
  watch: {
    // "$store.state.areaList": function (value) {
    //     this.initItems();
    // },
    // "$store.state.areaLedgerType": function (value) {
    //     this.initItems();
    // },
  },
  mounted() {
    this.getCostType()
    this.getProvince()
    this.getList()
    document.addEventListener('paste', this.handlePaste)
  },
  created() {
    const { authorityList = [] } = quinn.getStorage('userData')
    this.authority = authorityList
    this.getTypeList()
  },
  methods: {
    addRecord() {
      this.ledgerStatus = true
      this.preSalesImg = []
      this.createForm = this.$options.data.call(this).createForm
    },
    getTypeList() {
      this.$api.newAfterSaleTypesEnum().then((res) => {
        this.SaleTypeData = res
      })
    },
    approval(row) {
      this.approvalId = row.id
      this.adiutDialog = true
      this.preSalesImg = []
      this.reason = ''
    },
    searchList() {
      this.params.pageNumber = 1
      this.getList()
    },
    getList() {
      this.$api.areaLedgerAreaLedgerList(this.params).then((res) => {
        this.totalCount = res.total
        res.data.map((el) => {
          if (el.imgs) {
            el.preImg = el.imgs.split(',')
            el.preImg.forEach((val) => {
              this.previewImg.push('https://' + val)
            })
          }
        })
        this.dataList = res.data
      })
    },
    getProvince() {
      this.$api.areaLedgerAreaList().then((res) => {
        this.provinceOptions = res
      })
    },
    getCostType() {
      this.$api.areaLedgerFyTypeList().then((res) => {
        this.typeOptions = res
      })
    },
    _edit(row) {
      this.ledgerStatus = true
      Object.keys(this.createForm).forEach((key) => {
        if (row.hasOwnProperty(key)) {
          this.createForm[key] = row[key]
          this.createForm.optioner = row.optioner.toString()
          this.createForm.provinceId = row.area
          this.createForm.price = row.amount
          const matched = this.typeOptions.find(
            (item) => item.label === row.type
          )
          if (matched) {
            this.createForm.typeId = matched.value
          }
          this.preSalesImg = row.imgs.split(',')
        }
      })
    },
    submitCreateForm() {
      if (this.loading) return
      for (let i in this.createForm) {
        if (this.createForm[i] == '') {
          this.$message.error('请检查信息!')
          return
        }
      }
      let params = {
        type: this.createForm.typeId,
        remark: this.createForm.remark,
        optioner: this.createForm.optioner,
        area: this.createForm.provinceId,
        imgs: this.preSalesImg.toString(),
        amount: this.createForm.price,
      }
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 7000)
      this.$api.areaLedgerAddAreaLedger(params).then((res) => {
        this.$message({ message: '提交成功！', type: 'success' })
        this.ledgerStatus = false
        this.getList()
      })
    },
    handleSizeChange(e) {
      this.params.pageSize = e
      this.getList()
    },
    handleCurrentChange(e) {
      this.params.pageNumber = e
      this.getList()
    },
    // getUrl(e) {
    //     this.createForm.voucher = e[0];
    // }
    deletePic(i) {
      this.preSalesImg.splice(i, 1)
    },
    handlePaste(event) {
      if (!(this.ledgerStatus || this.adiutDialog)) return
      const clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file)
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
        .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            token: store.state.token,
          },
        })
        .then((response) => {
          this.preSalesImg.push(response.data.result[0])
          //this.preSalesImgList.push('https://' + response.data.result[0]);
        })
        .catch((error) => {})
    },
    deleteList(row) {
      const data = {
        id: row.id,
      }
      this.$api.areaLedgerDeleteOrUpdateAreaLedger(data).then((res) => {
        if (res == 1) {
          this.$message.success('删除成功！')
          document.body.click()
          this.getList()
        }
      })
    },
    review(row, val) {
      const data = {
        status: val,
        id: this.approvalId || row.id,
        paymentImg: this.preSalesImg.toString(),
        reason: this.reason,
      }
      if (val == 0) {
        delete data.reason
        delete data.paymentImg
      }
      this.$api.areaLedgerUpdateAreaLedgerStatus(data).then((res) => {
        if (res == 1) {
          this.$message.success('审核成功！')
          this.adiutDialog = false
          this.getList()
        }
      })
    },
    getImageBase64(url) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.onload = function () {
          const canvas = document.createElement('canvas')
          canvas.width = img.width
          canvas.height = img.height
          const ctx = canvas.getContext('2d')
          ctx.drawImage(img, 0, 0)
          resolve(canvas.toDataURL('image/png'))
        }
        img.onerror = reject
        img.src = url
      })
    },
    async _downLoad2() {
      console.log('ERERER')
      const loadingPage = this.$loading({
        lock: true,
        text: '正在导出，请稍等~',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const res = await this.$api
        .areaLedgerAreaLedgerList({
          pageNumber: 1,
          pageSize: 10000,
          type: this.params.type,
          area: this.params.area,
          status: this.params.status,
          userName: this.params.userName || '',
        })
        .then()
      // this.$message('正在导出，请稍等~')
      console.log('查询', res)

      const workbook = new ExcelJS.Workbook()
      const worksheet = workbook.addWorksheet('Sheet1')
      const headers = [
        '创建时间',
        '仓库',
        '类型',
        '备注',
        '金额',
        // '凭证',
        '财务打款',
      ]

      // 添加标题行
      const titleRow = worksheet.addRow(headers)

      // 设置列宽
      worksheet.columns = headers.map((item, index) => {
        if (index == 5) {
          // 凭证和财务打款列设置更宽
          return {
            width: 80,
            alignment: { vertical: 'middle', horizontal: 'center' },
          }
        }
        if (index == 3) {
          // 备注列
          return {
            width: 100,
            alignment: { vertical: 'middle', horizontal: 'center' },
          }
        } else {
          return {
            width: 20,
            alignment: { vertical: 'middle', horizontal: 'center' },
          }
        }
      })

      // 设置首行样式
      titleRow.eachCell((cell) => {
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'rgb(102, 177, 255)' },
        }
        cell.font = {
          bold: true,
          color: { argb: 'FFFFFF' },
        }
        cell.alignment = { vertical: 'middle', horizontal: 'center' }
      })

      for (const el of res.data) {
        const row = worksheet.addRow([
          el.createdAt,
          el.areaName,
          el.type,
          el.remark,
          el.amount,
          // '', // 凭证图片位置
          '', // 财务打款图片位置
        ])
        // if (el.imgs) {
        //   el.imgs = el.imgs.split(',')
        // }
        // // 处理图片数组
        // const images = Array.isArray(el.imgs)
        //   ? el.imgs
        //   : el.imgs
        //   ? [el.imgs]
        //   : []
        var images1 = []
        if (el.status != '1' && el.status != 0) {
          images1 = Array.isArray(el.paymentImg)
            ? el.paymentImg
            : el.paymentImg
            ? [el.paymentImg]
            : []
        }

        const imageHeight = 60
        const imageWidth = 80

        // 处理凭证图片（第6列，索引5）
        // if (images.length > 0) {
        //   // 设置合适的行高
        //   worksheet.getRow(row.number).height = imageHeight + 20

        //   for (let i = 0; i < images.length; i++) {
        //     try {
        //       const base64 = await this.getImageBase64('https://' + images[i])
        //       const imageId = workbook.addImage({
        //         base64: base64,
        //         extension: 'png',
        //       })

        //       // 使用相对列定位，每张图片向右偏移0.25列
        //       const colOffset = 5 + i * 0.25
        //       worksheet.addImage(imageId, {
        //         tl: { col: colOffset, row: row.number - 1 },
        //         ext: { width: imageWidth, height: imageHeight },
        //         editAs: 'oneCell',
        //       })
        //     } catch (err) {
        //       console.warn('凭证图片插入失败:', 'https://' + images[i], err)
        //     }
        //   }
        // }

        // 处理财务打款图片（第7列，索引6）
        if (images1.length > 0) {
          // 确保行高足够
          const currentHeight = worksheet.getRow(row.number).height
          const neededHeight = imageHeight + 20
          if (!currentHeight || currentHeight < neededHeight) {
            worksheet.getRow(row.number).height = neededHeight
          }

          for (let i = 0; i < images1.length; i++) {
            try {
              const base64 = await this.getImageBase64('https://' + images1[i])
              const imageId = workbook.addImage({
                base64: base64,
                extension: 'png',
              })

              // 使用相对列定位，每张图片向右偏移0.25列
              const colOffset = 5 + i * 0.25
              worksheet.addImage(imageId, {
                tl: { col: colOffset, row: row.number - 1 },
                ext: { width: imageWidth, height: imageHeight },
                editAs: 'oneCell',
              })
            } catch (err) {
              console.warn(
                '财务打款图片插入失败:',
                'https://' + images1[i],
                err
              )
            }
          }
        }
      }

      const buffer = await workbook.xlsx.writeBuffer()
      saveAs(new Blob([buffer]), `仓库费用数据.xlsx`)
      loadingPage.close()
    },
    // 下载
    async _downLoad() {
      const res = await this.$api
        .areaLedgerAreaLedgerList({
          pageNumber: 1,
          pageSize: 10000,
          type: this.params.type,
          area: this.params.area,
          status: this.params.status,
          userName: this.params.userName || '',
        })
        .then()
      this.$message('正在导出，请稍等~')
      console.log('查询', res)

      const workbook = new ExcelJS.Workbook()
      const worksheet = workbook.addWorksheet('Sheet1')
      const headers = [
        '创建时间',
        '仓库',
        '类型',
        '备注',
        '金额',
        '凭证',
        '财务打款',
      ]
      // 添加标题行
      const titleRow = worksheet.addRow(headers)
      // 设置列宽
      worksheet.columns = headers.map((item, index) => {
        if (index == 5 || index == 6) {
          // 交易截图
          return {
            width: 40,
            alignment: { vertical: 'middle', horizontal: 'center' }, // 所有列居中
          }
        }
        if (index == 3) {
          // 交易截图
          return {
            width: 80,
            alignment: { vertical: 'middle', horizontal: 'center' }, // 所有列居中
          }
        } else {
          return {
            width: 20,
            alignment: { vertical: 'middle', horizontal: 'center' }, // 所有列居中
          }
        }
      })

      // 设置首行样式：紫色背景、白色加粗字体、居中
      titleRow.eachCell((cell) => {
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'rgb(102, 177, 255)' },
        }
        cell.font = {
          bold: true,
          color: { argb: 'FFFFFF' },
        }
        cell.alignment = { vertical: 'middle', horizontal: 'center' }
      })

      for (const el of res.data) {
        const row = worksheet.addRow([
          el.createdAt,
          el.areaName,
          el.type,
          el.remark,
          el.amount,
          '', // 凭证图片位置
          '', // 财务打款图片位置
        ])
        if (el.imgs) {
          el.imgs = el.imgs.split(',')
        }
        const images = Array.isArray(el.imgs)
          ? el.imgs
          : el.imgs
          ? [el.imgs]
          : []
        const images1 = Array.isArray(el.paymentImg)
          ? el.paymentImg
          : el.paymentImg
          ? [el.paymentImg]
          : []
        const imageHeight = 80
        const imageWidth = 100
        const gap = 50
        let totalWidth = images.length * (imageWidth + gap)
        if (images.length > 0) {
          worksheet.getRow(row.number).height = imageHeight + 10
          for (let i = 0; i < images.length; i++) {
            try {
              const base64 = await this.getImageBase64('https://' + images[i])
              const imageId = workbook.addImage({
                base64: base64,
                extension: 'png',
              })
              worksheet.addImage(imageId, {
                tl: {
                  col: 5 + i * 0.99, // 控制偏移列位置（让图片横向排列在一格里）
                  row: row.number - 1,
                },
                ext: { width: imageWidth, height: imageHeight },
              })
            } catch (err) {
              console.warn('图片插入失败:', 'https://' + images[i], err)
            }
          }
        }
        if (images1.length > 0) {
          worksheet.getRow(row.number).height = imageHeight + 10
          for (let i = 0; i < images1.length; i++) {
            try {
              const base64 = await this.getImageBase64('https://' + images1[i])
              const imageId = workbook.addImage({
                base64: base64,
                extension: 'png',
              })
              worksheet.addImage(imageId, {
                tl: {
                  col: 6 + i * 0.99, // 控制偏移列位置（让图片横向排列在一格里）
                  row: row.number - 1,
                },
                ext: { width: imageWidth, height: imageHeight },
              })
            } catch (err) {
              console.warn('图片插入失败:', 'https://' + images1[i], err)
            }
          }
        }
      }
      const buffer = await workbook.xlsx.writeBuffer()

      saveAs(new Blob([buffer]), `仓库费用数据.xlsx`)
    },
  },
}
</script>
<style lang="less" scoped>
/* 固定合计行的位置 */
.main /deep/ .el-table .el-table__footer-wrapper .cell {
  text-align: center;
}
</style>
